package com.ysz.timewheel.server.conn;

import com.ysz.timewheel.TimeWheel;
import com.ysz.timewheel.server.struct.ClientStruct;
import com.ysz.timewheel.server.task.AcceptTask;
import com.ysz.timewheel.server.threadpool.ThreadPool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;

/**
 * @ClassName ServerConn
 * @Description 服务端接收请求
 * @Data 17:39
 * @Version 1.0
 * @Author ysz
 */
public class ServerConn {

    /**
     * 注册  客户端向该接口进行注册  该接口hold住请求实现长轮询
     *
     * @return 1-超时返回 2-provider节点异常consumer去重新拉取节点信息
     * @author ysz
     */
    public int accept(ClientStruct clientStruct) {
        try {
            //设置当前线程 方便在acceptTask中做中断
            clientStruct.setThread(Thread.currentThread());
            //时间轮节点添加
            TimeWheel timeWheel = new TimeWheel();
            Integer currIndex = timeWheel.register(clientStruct);
            AcceptTask acceptTask = new AcceptTask();
            acceptTask.setCurrIndex(currIndex);
            acceptTask.setClientStruct(clientStruct);
            //添加到队列
            AcceptTask.getLinkedBlockingQueue().put(acceptTask);
            try {
                //使用睡眠hold住30秒
                Thread.sleep(30000);
                //睡完了醒来直接中断自己
                Thread.currentThread().interrupt();
                return 1;
            } catch (Exception e) {
                //catch住中断异常不做处理
                System.out.println("中断异常====》" + e.getMessage());
            }
            return acceptTask.getReturnCode();
        } catch (Exception e) {
            return 2;
        }
    }
}
